package com.upeoe.shiro.chapter5.dao.impl;

import com.upeoe.shiro.chapter5.dao.RoleDao;
import com.upeoe.shiro.chapter5.entity.Role;
import com.upeoe.shiro.chapter5.utils.JdbcTemplateUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author ven_hxz
 * @create 2016-07-05 下午2:08
 */
public class RoleDaoImpl implements RoleDao {

    private JdbcTemplate jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();

    public Role createRole(final Role role) {
        final String sql = "insert into sys_roles(role, description, available) values(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, new String[]{"id"});
                ps.setString(1, role.getRole());
                ps.setString(2, role.getDescription());
                ps.setBoolean(3, role.getAvailable());
                return ps;
            }
        }, keyHolder);

        role.setId(keyHolder.getKey().longValue());
        return role;
    }

    public void deleteRole(Long roleId) {
        String sql = "delete from sys_users_roles where role_id";
        jdbcTemplate.update(sql, roleId);

        sql = "delete from sys_roles where id = ?";
        jdbcTemplate.update(sql, roleId);
    }

    public void addRelationPermissions(Long roleId, Long... permissionIds) {
        if (permissionIds == null || permissionIds.length == 0) return;

        String sql = "insert into sys_roles_permissions(role_id, permission_id) values(?, ?)";

        for (Long permissionId : permissionIds) {
            if (!isExists(roleId, permissionId)) {
                jdbcTemplate.update(sql, roleId, permissionId);
            }
        }
    }

    public void removeRelationPermissions(Long roleId, Long... permissionIds) {
        if (permissionIds == null || permissionIds.length == 0) return;

        String sql = "delete from sys_roles_permissions where role_id and permission_id = ?";

        for (Long permissionId : permissionIds) {
            if (isExists(roleId, permissionId)) {
                jdbcTemplate.update(sql, roleId, permissionId);
            }
        }
    }

    private boolean isExists(Long roleId, Long permissionId) {
        String sql = "select count(1) from sys_roles_permissions where " +
                "role_id = ? and permission_id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, roleId, permissionId) != 0;
    }
}
